#include "tcp_task.h"
#include <string.h>
#include <stdlib.h>
#include "lwip.h"
#include "lwip/sockets.h"
#include "lwip/opt.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "lwip/api.h"
#include "BspM1_Driver.h"
#include "lwip/inet.h"
#include "lwip/netdb.h"
#include "tcp_transfer.h"


#define LWIP_DEMO_PORT 8080
#define LWIP_DEMO_RX_BUFSIZE         200    /* 最大接收数据长度 */
#define IP_ADDR   "192.168.3.5"/*client 服务端ip*/
//osMessageQueueId_t tcpQueueHandle;
//osThreadId_t tcpClientTaskHandle;
extern struct netconn *shared_conn;
int shared_sock = -1;
int InitConnection() {
//    // 创建 TCP 连接
//    shared_conn = netconn_new(NETCONN_TCP);
//    if (shared_conn != NULL) {
//        // 连接到服务器
//        ip_addr_t server_ip;
//        IP4_ADDR(&server_ip, 192, 168, 0, 200); // 服务器 IP 地址
//        err_t err = netconn_connect(shared_conn, &server_ip, 5001); // 连接到服务器的端口
//        if (err != ERR_OK) {
//            // 处理连接错误
//            netconn_delete(shared_conn);
//            shared_conn = NULL;
//        }
//    } else {
//        // 处理连接创建失败
//    }
	struct sockaddr_in server_addr;
    int sockfd;
    int flags;

    // 创建 TCP 套接字
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {

        return -1;
    }

    // 设置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(5001);
    inet_pton(AF_INET, "192.168.0.200", &server_addr.sin_addr);

    // 设置为非阻塞模式
    flags = fcntl(sockfd, F_GETFL, 0);
    fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

    // 尝试连接服务器
    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        if (errno != EINPROGRESS) {

            close(sockfd);
            return -1;
        }
    }

    shared_sock = sockfd;
    return 0;
}

void TCPReceiveTask(void *argument) {
    uint8_t buffer[TRANSFER_SEND_SIZE_MAX];
    int len;
    Send_Data sendData;
//    char msg[] = "你好";

	uint8_t id_transfered = 0;
	uint32_t uniqueID[3];
	uniqueID[0] = *(uint32_t*)0x1FFF7A10;
	uniqueID[1] = *(uint32_t*)0x1FFF7A14;
	uniqueID[2] = *(uint32_t*)0x1FFF7A18;
	
    struct pollfd fds[1];

    while (1) {
        if (shared_sock < 0) {
            if (InitConnection() < 0) {
                osDelay(1000); // 延时后重试
                continue;
            }
        }

        // 设置 poll 结构体
        fds[0].fd = shared_sock;
        fds[0].events = POLLIN | POLLOUT | POLLERR;

        int ret = poll(fds, 1, 100);  // 1 秒超时

        if (ret < 0) {
//            perror("poll error");
            close(shared_sock);
						id_transfered = 0;
            shared_sock = -1;
            osDelay(1000);  // 延时后重试
            continue;
        } else if (ret == 0) {
            // 超时
            continue;
        } else {
            if (fds[0].revents & POLLERR) {
                // 处理异常事件
//                perror("poll error event");
                close(shared_sock);
								id_transfered = 0;
                shared_sock = -1;
                osDelay(1000);  // 延时后重试
                continue;
            }

            if (fds[0].revents & POLLIN) {
                // 套接字可读
                len = recv(shared_sock, buffer, sizeof(buffer), 0);
                if (len < 0) {
                    if (errno == EWOULDBLOCK || errno == EAGAIN) {
                        osDelay(10); // 无数据可读，稍后再试
                        continue;
                    } else {
//                        perror("recv error");
                        close(shared_sock);
												id_transfered = 0;
                        shared_sock = -1;
                        osDelay(1000);  // 延时后重试
                        continue;
                    }
                } else if (len > 0) {
//                    if (osMessageQueuePut(motorQueueHandle, buffer, 0, 0) != osOK) {
//                        // 处理消息队列错误
//                    }
									transfer_input(buffer,len);
                }
            }

            if (fds[0].revents & POLLOUT) {
							if(id_transfered == 0)
							{
								id_transfered = 1;
								tcp_transfer_push(RPLY_ID,uniqueID,sizeof(uniqueID));
							}
                // 套接字可写
//                if (osMessageQueueGet(tcpQueueHandle, &sendData, NULL, 0) == osOK) 
							uint16_t send_len = tcp_get_send(buffer);
									if(send_len != 0)
									{
                    len = send(shared_sock, buffer, send_len, 0);
                    if (len < 0) {
                        if (errno == EWOULDBLOCK || errno == EAGAIN) {
                            // 套接字暂时不可写，稍后再试
                            osDelay(10);
                            continue;
                        } else {
//                            perror("send error");
                            close(shared_sock);
														id_transfered = 0;
                            shared_sock = -1;
                            osDelay(1000);  // 延时后重试
                            continue;
                        }
                    }
                }
            }
        }

        // 延时以避免占用过多 CPU 时间
        osDelay(10);
    }
}
